package pt.iscte.pcd.project.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.LinkedList;

import pt.iscte.pcd.project.order.Order;
import pt.iscte.pcd.project.userInterface.GUI;

public class DealWithServer {
	private LinkedList<Order> listaRecebidos = new LinkedList<Order>() ;
	private LinkedList<Order> listaAEnviar = new LinkedList<Order>();
	private Socket socketClient;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private DealWithServerReceiver receiver;
	private DealWithServerSender sender;
	private GUI gui;
	
	
	public DealWithServer(Socket socketClient, GUI gui) {
		this.socketClient= socketClient;
		this.setGui(gui);
		try {

			setOut(new ObjectOutputStream(getSocketClient().getOutputStream()));
			setIn(new ObjectInputStream(getSocketClient().getInputStream()));
			receiver = new DealWithServerReceiver(this);
			sender = new DealWithServerSender(this);
			receiver.start();
			sender.start();
			
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public synchronized void porPedidosNaListaRecebidos(Order order) {
		listaRecebidos.add(order);
		notifyAll();

	}

	public synchronized Order retiraPedidosDaListaAEnviar() throws InterruptedException{
		while(listaAEnviar.isEmpty()){
			wait();

		}
		return listaAEnviar.poll();
	}


	public synchronized void porPedidosNaListaAEnviar(Order order){
		listaAEnviar.add(order);
		notifyAll();
	}

	public synchronized Order retiraPedidosDaListaRecebidos() throws InterruptedException{
		while(listaRecebidos.isEmpty()){
			wait();
		}
		return listaRecebidos.poll();
	}




	public LinkedList<Order> getListaAReceber() {
		return listaRecebidos;
	}

	public void setListaAReceber(LinkedList<Order> listaAReceber) {
		this.listaRecebidos = listaAReceber;
	}

	public LinkedList<Order> getListaAEnviar() {
		return listaAEnviar;
	}

	public void setListaAEnviar(LinkedList<Order> listaAEnviar) {
		this.listaAEnviar = listaAEnviar;
	}

	public Socket getSocketClient() {
		return socketClient;
	}

	public void setSocketClient(Socket socketClient) {
		this.socketClient = socketClient;
	}

	public ObjectInputStream getIn() {
		return in;
	}

	public void setIn(ObjectInputStream in) {
		this.in = in;
	}

	public ObjectOutputStream getOut() {
		return out;
	}

	public void setOut(ObjectOutputStream out) {
		this.out = out;
	}

	public GUI getGUI() {
		return gui;
	}

	public void setGui(GUI gui) {
		this.gui = gui;
	}






}
